import { define } from 'cydon'
import { Task, World } from '../type'
import { CTable } from './CTable'
import { clearData, del, list, save } from '../store'
import { autoload, pickName, processData } from '../util'
import { CPagination } from './CPagination'
import { DataFilter } from './DataFilter'
import { WorldSettings } from './WorldSettings'
import 'uno.css'
import 'virtual:unocss-devtools'

export const settings = <WorldSettings>document.querySelector('[is=world-settings]')

/**
 * @element world-list
 * 存档列表
 */
@define('world-list')
export class WorldList extends CTable<World> {
	/** 全选 */
	get selectAll() {
		return this.items.length > 0 && this.items.every(x => x.selected)
	}
	set selectAll(value) {
		this.items.forEach(x => x.selected = value)
	}

	/** 选中的存档数量 */
	get selectedCount() {
		return this.items.filter(x => x.selected).length
	}

	async connectedCallback() {
		await autoload()
		super.connectedCallback()
	}

	/** 获取时间 */
	time(val: number) {
		return new Date(val).toLocaleString()
	}

	/** 创建新存档 */
	async create() {
		const item = <World>{
			name: pickName(),
			mode: 1,
			difficulty: 1,
			created: +new Date,
			updated: 0,
			opts: 12,
			data: <Uint8Array[]>[],
			tasks: <Task[]>[],
			techs: new Set,
			stats: {
				playTime: 0,
				totalCollect: 0,
				totalBuild: 0,
				totalUpgrade: 0,
				totalDestroy: 0
			}
		}
		const name = await this.modify(item)
		if (name) {
			this.items.push(item)
			await save(item)
			this.load(item)
		}
	}

	/** 加载存档 */
	load(item: World) {
		sessionStorage.setItem('world', item.name)
		location.href = './game.html'
	}

	/** 修改存档 */
	modify(item: World) {
		let resolve: (name: string) => void
		const p = new Promise<string>(r => resolve = r)
		Object.assign(settings.data, item)
		settings.addEventListener('close', () => {
			if (settings.name) {
				const time = +new Date
				item.name = settings.name
				item.mode = settings.mode
				item.difficulty = settings.difficulty
				item.seed = settings.seed
				item.mapSize = settings.mapSize
				item.updated = time
			}
			resolve(settings.name)
		}, { once: true })
		settings.showModal()
		return p
	}

	/** 删除选中的存档 */
	del() {
		if (confirm('确定要删除选中的存档吗？')) {
			for (let i = this.items.length; --i >= 0;) {
				const item = this.items[i]
				if (item.selected) {
					this.items.splice(i, 1)
					del(item.name)
				}
			}
			// TODO
			location.reload()
		}
	}

	/** 删除当前页的所有存档 */
	delPage() {
		if (confirm('确定要删除当前页的所有存档吗？')) {
			for (const item of this.items) {
				del(item.name)
			}
			// TODO
			location.reload()
			//this.items = []
		}
	}

	/** 删除所有存档 */
	delAll() {
		if (confirm('确定要删除所有存档吗？')) {
			clearData().then(() => {
				location.reload()
			})
		}
	}

	async updateContents(p: CPagination, f?: DataFilter) {
		this.items = processData(await list(), p, f)
	}
}

declare global {
	interface HTMLElementTagNameMap {
		'world-list': WorldList
	}
}
